package com.xnyzc.lhy.mis.service.impl.cms.user.wallet;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xnyzc.lhy.common.component.convert.DateToStringConverter;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.wallet.EIsTransaction;
import com.xnyzc.lhy.common.penum.wallet.ERecordType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.param.cms.PageVo;
import com.xnyzc.lhy.mis.entity.param.cms.user.wallet.CmsOacUserOrderPaymentParam;
import com.xnyzc.lhy.mis.entity.result.cms.user.CmsOacUserRechargeListRes;
import com.xnyzc.lhy.mis.entity.user.OaCUser;
import com.xnyzc.lhy.mis.entity.user.wallet.OaCWalletRecord;
import com.xnyzc.lhy.mis.mapper.user.OaCUserMapper;
import com.xnyzc.lhy.mis.mapper.user.wallet.OaCWalletRecordMapper;
import com.xnyzc.lhy.mis.service.cms.user.wallet.IOacUserOrderPaymentRecordService;
import com.xnyzc.lhy.mis.service.cms.util.IOaSysGetOfficeIdListService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 订单流水记录管理
 * @Author conglijuan
 * @Date 2019-08-20 16:00
 **/
@Service
public class OacUserOrderPaymentRecordServiceImpl implements IOacUserOrderPaymentRecordService {

    @Autowired
    private IOaSysGetOfficeIdListService iOaSysGetOfficeIdListService;
    @Autowired
    private OaCUserMapper oacUserMapper;
    @Autowired
    private OaCWalletRecordMapper oacWalletRecordMapper;


    /**
     * 获取订单流水列表
     * @param cmsOacUserOrderPaymentParam
     * @return
     */
    @Override
    public Rv getOrderPaymentRecordList(CmsOacUserOrderPaymentParam cmsOacUserOrderPaymentParam){
        Integer page=cmsOacUserOrderPaymentParam.getPage();
        Integer pageSize=cmsOacUserOrderPaymentParam.getPageSize();
        String mobileAccount=cmsOacUserOrderPaymentParam.getMobileAccount();
        String userName=cmsOacUserOrderPaymentParam.getUserName();
        String orderNo=cmsOacUserOrderPaymentParam.getOrderNo();
        Long sysUserId= TokenUtil.getTokenUserId();
        List<String> dataScope=TokenUtil.getRoleDataScope();
        if(CheckUtil.objIsEmpty(page)||CheckUtil.objIsEmpty(pageSize)||CheckUtil.objIsEmpty(dataScope)||CheckUtil.objIsEmpty(sysUserId)){
            throw PangException.create(EErrorCode.missingArg);
        }
        List<CmsOacUserRechargeListRes> resultList=new ArrayList<>();
        PageVo pageVo = new PageVo();
        pageVo.setItems(resultList);
        pageVo.setTotal(0L);
        List<Long> selectCuserIdList=iOaSysGetOfficeIdListService.selectCUserIdList(sysUserId,dataScope);
        if(CheckUtil.objIsEmpty(selectCuserIdList)){
            return Rv.wrap(pageVo);
        }
        //分页查询用户充值记录
        IPage<OaCWalletRecord> oacWalletRecordIPage=getUserWalletRecordList(orderNo,userName,mobileAccount,selectCuserIdList,page,pageSize);
        if(CheckUtil.objIsEmpty(oacWalletRecordIPage)){
            return Rv.wrap(oacWalletRecordIPage);
        }
        //通过userID查询用户信息
        List<Long> idList=new ArrayList<>();
        for(OaCWalletRecord r:oacWalletRecordIPage.getRecords()) {
            idList.add(r.getUserId());
        }
        List<OaCUser> userList=getOacUserListByIdList(idList);
        //返回结果
        CmsOacUserRechargeListRes result=null;
        for(OaCWalletRecord r:oacWalletRecordIPage.getRecords()){
            result=new CmsOacUserRechargeListRes();
            result.setDiscountedAmount(new BigDecimal(0));
            result.setRecordId(r.getRecordId());
            result.setActualAmount(r.getActualAmount());
            result.setDeptOfficialBalance(r.getDeptOfficialBalance());
            if(CheckUtil.objIsNotEmpty(r.getDiscountedAmount())){
                result.setDiscountedAmount(r.getDiscountedAmount());
            }
            result.setWalletBalance(r.getWalletBalance());
            result.setOrderNo(r.getOrderNo());
            result.setPersonalOfficialBalance(r.getPersonalOfficialBalance());
            result.setTransactionOrderNo(r.getTransactionOrderNo());
            result.setTransactionSerialNo(r.getTransactionSerialNo());
            result.setTransactionTime(new DateToStringConverter().convert(r.getTransactionTime()));
            result.setRecordType(ERecordType.findById(r.getRecordType()).getValue());
            result.setIsTransaction(EIsTransaction.findById(r.getIsTransaction()).getDesc());
            if(!userList.isEmpty()){
                for(OaCUser u:userList){
                    if(u.getUserId().equals(r.getUserId())){
                        result.setUserName(u.getUserName());
                        result.setMobileAccount(u.getUserPhone());
                    }
                }
            }

            resultList.add(result);
        }
        pageVo.setItems(resultList);
        pageVo.setTotal(oacWalletRecordIPage.getTotal());
        return Rv.wrap(pageVo);
    }

    /**
     * 查询用户充值记录列表
     @param userName
      * @param mobile
     * @param page
     * @param pageSize
     * @return
     */
    private IPage<OaCWalletRecord> getUserWalletRecordList(String orderNo,String userName, String mobile, List<Long> selectUserIdList, Integer page, Integer pageSize){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.orderByDesc(OaCWalletRecord.CREATE_TIME);
        queryWrapper.eq(OaCWalletRecord.TAG, TokenUtil.getTag());
        queryWrapper.in(OaCWalletRecord.USER_ID,selectUserIdList);
        if(StringUtils.isNotBlank(orderNo)){
            queryWrapper.like(OaCWalletRecord.ORDER_NO, orderNo);
        }
        if(CheckUtil.objIsNotEmpty(userName)||CheckUtil.objIsNotEmpty(mobile)){
            //通过姓名或者手机号码查询用户信息d
            List<OaCUser> userList=getOacUserListByName(userName,mobile);
            if(CheckUtil.objIsEmpty(userList)){
                return  null;
            }
            List<Long> idList=new ArrayList<>();
            for(OaCUser v:userList){
                idList.add(v.getUserId());
            }
            queryWrapper.in(OaCWalletRecord.USER_ID,idList);
        }
        //交易类型
        List<Integer> typeList=new ArrayList<>();
        typeList.add(ERecordType.moneyDisbursement.getType());
        typeList.add(ERecordType.alipayDisbursement.getType());
        typeList.add(ERecordType.weChatDisbursement.getType());
        typeList.add(ERecordType.officialDisbursement.getType());
        typeList.add(ERecordType.myDisbursement.getType());
        queryWrapper.in(OaCWalletRecord.RECORD_TYPE,typeList);
        IPage<OaCWalletRecord> iPage = new Page<>();
        iPage.setCurrent(page);
        iPage.setSize(pageSize);
        IPage<OaCWalletRecord> list=oacWalletRecordMapper.selectPage(iPage, queryWrapper);
        return list;
    }

    /**
     * 通过姓名或者手机号码查询用户
     * @param userName
     * @return
     */
    private List<OaCUser> getOacUserListByName(String userName,String mobileAccount){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.orderByDesc(OaCUser.CREATE_TIME);
        queryWrapper.eq(OaCUser.TAG,TokenUtil.getTag());
        if(CheckUtil.objIsNotEmpty(userName)){
            queryWrapper.like(OaCUser.USER_NAME,userName);
        }
        if(CheckUtil.objIsNotEmpty(mobileAccount)){
            queryWrapper.like(OaCUser.USER_PHONE,mobileAccount);
        }
        List<OaCUser> list=oacUserMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 通过id查询用户信息
     * @param idList
     * @return
     */
    private List<OaCUser> getOacUserListByIdList(List<Long> idList){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.orderByDesc(OaCUser.CREATE_TIME);
        queryWrapper.eq(OaCUser.TAG,TokenUtil.getTag());
        queryWrapper.in(OaCUser.USER_ID,idList);
        List<OaCUser> list=oacUserMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 获取订单流水列表
     * @param cmsOacUserOrderPaymentParam
     * @return
     */
    @Override
    public Rv exportOrderPaymentExcel(CmsOacUserOrderPaymentParam cmsOacUserOrderPaymentParam){
        String mobileAccount=cmsOacUserOrderPaymentParam.getMobileAccount();
        String userName=cmsOacUserOrderPaymentParam.getUserName();
        String orderNo=cmsOacUserOrderPaymentParam.getOrderNo();
        Long sysUserId= TokenUtil.getTokenUserId();
        List<String> dataScope=TokenUtil.getRoleDataScope();
        if(CheckUtil.objIsEmpty(dataScope)||CheckUtil.objIsEmpty(sysUserId)){
            throw PangException.create(EErrorCode.missingArg);
        }
        List<CmsOacUserRechargeListRes> resultList=new ArrayList<>();
        List<Long> selectCuserIdList=iOaSysGetOfficeIdListService.selectCUserIdList(sysUserId,dataScope);
        if(CheckUtil.objIsEmpty(selectCuserIdList)){
            return Rv.wrap(EErrorCode.success,resultList);
        }
        //分页查询用户充值记录
        List<OaCWalletRecord> oacWalletRecordIPage=geExportWalletRecordList(orderNo,userName,mobileAccount,selectCuserIdList);
        if(CheckUtil.objIsEmpty(oacWalletRecordIPage)){
            return Rv.wrap(EErrorCode.success,resultList);
        }
        //通过userID查询用户信息
        List<Long> idList=new ArrayList<>();
        for(OaCWalletRecord r:oacWalletRecordIPage) {
            idList.add(r.getUserId());
        }
        List<OaCUser> userList=getOacUserListByIdList(idList);
        //返回结果
        CmsOacUserRechargeListRes result=null;
        for(OaCWalletRecord r:oacWalletRecordIPage){
            result=new CmsOacUserRechargeListRes();
            result.setRecordId(r.getRecordId());
            result.setActualAmount(r.getActualAmount());
            result.setDeptOfficialBalance(r.getDeptOfficialBalance());
            result.setDiscountedAmount(r.getDiscountedAmount());
            result.setWalletBalance(r.getWalletBalance());
            result.setOrderNo(r.getOrderNo());
            result.setPersonalOfficialBalance(r.getPersonalOfficialBalance());
            result.setTransactionOrderNo(r.getTransactionOrderNo());
            result.setTransactionSerialNo(r.getTransactionSerialNo());
            result.setTransactionTime(new DateToStringConverter().convert(r.getTransactionTime()));
            result.setRecordType(ERecordType.findById(r.getRecordType()).getDesc());
            result.setIsTransaction(EIsTransaction.findById(r.getIsTransaction()).getDesc());
            if(CheckUtil.objIsNotEmpty(userList)){
                for(OaCUser u:userList){
                    if(u.getUserId().equals(r.getUserId())){
                        result.setUserName(u.getUserName());
                        result.setMobileAccount(u.getUserPhone());
                    }
                }
            }

            resultList.add(result);
        }
        return Rv.wrap(EErrorCode.success,resultList);
    }

    /**
     * 查询用户充值记录列表
     @param userName
      * @param mobile
     * @return
     */
    private List<OaCWalletRecord> geExportWalletRecordList(String orderNo,String userName, String mobile, List<Long> selectUserIdList){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.orderByDesc(OaCWalletRecord.CREATE_TIME);
        queryWrapper.eq(OaCWalletRecord.TAG, TokenUtil.getTag());
        queryWrapper.in(OaCWalletRecord.USER_ID,selectUserIdList);
        if(StringUtils.isNotBlank(orderNo)){
            queryWrapper.like(OaCWalletRecord.ORDER_NO,orderNo);
        }
        if(CheckUtil.objIsNotEmpty(userName)||CheckUtil.objIsNotEmpty(mobile)){
            //通过姓名或者手机号码查询用户信息d
            List<OaCUser> userList=getOacUserListByName(userName,mobile);
            if(CheckUtil.objIsEmpty(userList)){
                return  null;
            }
            List<Long> idList=new ArrayList<>();
            for(OaCUser v:userList){
                idList.add(v.getUserId());
            }
            queryWrapper.in(OaCWalletRecord.USER_ID,idList);
        }
        //交易类型
        List<Integer> typeList=new ArrayList<>();
        typeList.add(ERecordType.moneyDisbursement.getType());
        typeList.add(ERecordType.alipayDisbursement.getType());
        typeList.add(ERecordType.weChatDisbursement.getType());
        typeList.add(ERecordType.officialDisbursement.getType());
        typeList.add(ERecordType.myDisbursement.getType());
        queryWrapper.in(OaCWalletRecord.RECORD_TYPE,typeList);
        List<OaCWalletRecord> list=oacWalletRecordMapper.selectList(queryWrapper);
        return list;
    }

}
